#coding=utf-8

from django import template
from criterion.models import ReviewClause, ReviewKey, ReviewReference
from django.core.exceptions import ObjectDoesNotExist

register = template.Library()

@register.inclusion_tag('criterion/result.html') #引入模板html
def show_keys_and_refs(cid,is_superuser):
    clause=ReviewClause.objects.get(pk=cid)
    keys_A=ReviewKey.objects.filter(clause=cid,level="A").order_by('sort')
    keys_B=ReviewKey.objects.filter(clause=cid,level="B").order_by('sort')
    keys_C=ReviewKey.objects.filter(clause=cid,level="C").order_by('sort')
    _dict={'clause':clause,'keys_A':keys_A,'keys_B':keys_B,'keys_C':keys_C,'is_superuser':is_superuser}
    try:
        ref_A=ReviewReference.objects.get(clause=cid,type="A")
        _dict['ref_A']=ref_A
    except ObjectDoesNotExist:
        pass
    try:
        ref_B=ReviewReference.objects.get(clause=cid,type="B")
        _dict['ref_B'] = ref_B
    except ObjectDoesNotExist:
        pass
    try:
        ref_C=ReviewReference.objects.get(clause=cid,type="C")
        _dict['ref_C'] = ref_C
    except ObjectDoesNotExist:
        pass
    try:
        ref_D=ReviewReference.objects.get(clause=cid,type="D")
        _dict['ref_D'] = ref_D
    except ObjectDoesNotExist:
        pass
    return  _dict #返回字典


@register.filter
def get_level4_clause(value):
     return ReviewClause.objects.filter(level="4").filter(parent= value).order_by("sort")


@register.filter
def get_level6_clause(value):
     return ReviewClause.objects.filter(level="6").filter(parent= value).order_by("sort")


@register.filter
def get_clause_keys_count(value):
     return ReviewKey.objects.filter(clause=value).count()

@register.filter
def get_file_openurl(filename):
    office_url=r"https://view.officeapps.live.com/op/view.aspx?src=http://hams.tcpiptest.com/media/"
    image_url=r"http://hams.tcpiptest.com/media/"
    pdf_url=r"http://hams.tcpiptest.com/media/"
    ret=""
    #doc xls ppt
    if filename.endswith('.doc'):
        ret=office_url+filename
        return ret
    if filename.endswith('.docx'):
        ret=office_url+filename
        return ret
    if filename.endswith('.xls'):
        ret=office_url+filename
        return ret
    if filename.endswith('.xlsx'):
        ret=office_url+filename
        return ret
    if filename.endswith('.ppt'):
        ret=office_url+filename
        return ret
    if filename.endswith('.pptx'):
        ret=office_url+filename
        return ret
    #jpg png
    if filename.endswith('.jpg'):
        ret = image_url + filename
        return ret
    if filename.endswith('.jpeg'):
        ret = image_url + filename
        return ret
    if filename.endswith('.png'):
        ret = image_url + filename
        return ret
    if filename.endswith('.gif'):
        ret = image_url + filename
        return ret
    #pdf
    if filename.endswith('.pdf'):
        ret = pdf_url + filename
        return ret
    return ret
